﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Windows.System;
using Microsoft.Devices.Sensors;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Xna.Framework;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using 掌控校园.ViewModels;
using Color = System.Windows.Media.Color;

namespace 掌控校园
{
    public partial class CoursePage : PhoneApplicationPage
    {
        private string postdata;
        private string postback;



        private static bool IsCourseLoaded = false;

        private ApplicationBarMenuItem settingsMenuItem;
        private ApplicationBarMenuItem leadingInCourseMenuItem;
        private ApplicationBarMenuItem aboutMenuItem;

        public static SolidColorBrush[] CourseColorBrush = new SolidColorBrush[12];

        public static int ColorNum = 0;

        private static WeeklyCourses weeklyCourses;

        private Accelerometer _accelerometer;

        private Grid courseGrid;//奇怪这里为什么改成了static之后导航到下一个页面时课程会消失？？？？

        private static int currentPage = 0;

        public static WeeklyCourses MyWeeklyCourses
        {
            get
            {
                if (weeklyCourses != null)
                    return weeklyCourses;
                string dataFromIsoStore;
                if (IsolatedStorageSettings.ApplicationSettings.TryGetValue("ParsedWeek"+(App.WeekNumber-1).ToString(), out dataFromIsoStore))
                {
                    weeklyCourses = JsonConvert.DeserializeObject<WeeklyCourses>(dataFromIsoStore);
                    return weeklyCourses;
                }
                else
                {
                    MessageBox.Show("从独立存储中加载数据失败……请重新导入课表");
                    return null;
                }
            }
        }

        public CoursePage()
        {

            InitializeColor();

            #region 初始化颜色值
            try
            {
                ColorNum = Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["ColorNum"]);
            }
            catch (Exception)
            {

            }
            #endregion

            InitializeComponent();

            //DataContext = MyWeeklyCourses;

            this.BackKeyPress += CoursePage_BackKeyPress;


            #region 初始化应用程序栏
            ApplicationBar = new ApplicationBar();
            ApplicationBar.Opacity = 0.9;
            ApplicationBar.Mode = ApplicationBarMode.Minimized;
            ApplicationBar.ForegroundColor = Color.FromArgb((byte) 255, (byte) 0, (byte) 175, (byte) 240);
            ApplicationBar.BackgroundColor = Color.FromArgb((byte)0, (byte)0, (byte)175, (byte)240);

            
            settingsMenuItem = new ApplicationBarMenuItem("settings");
            settingsMenuItem.Click += settingsMenuItem_Click;
            leadingInCourseMenuItem = new ApplicationBarMenuItem("leading in");
            leadingInCourseMenuItem.Click += leadingInCourseMenuItem_Click;
            aboutMenuItem = new ApplicationBarMenuItem("about");
            aboutMenuItem.Click += aboutMenuItem_Click;
            ApplicationBar.MenuItems.Add(settingsMenuItem);
            ApplicationBar.MenuItems.Add(leadingInCourseMenuItem);
            ApplicationBar.MenuItems.Add(aboutMenuItem);


            ApplicationBar.StateChanged += ApplicationBar_StateChanged;



            #endregion

            _accelerometer = new Accelerometer();
            _accelerometer.CurrentValueChanged += _accelerometer_CurrentValueChanged;
            _accelerometer.TimeBetweenUpdates = new TimeSpan(2000);


        }

        void _accelerometer_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => ProcessorAccelerometerReading(e));

        }

        private void ProcessorAccelerometerReading(SensorReadingEventArgs<AccelerometerReading> e)
        {
            if (e.SensorReading.Acceleration.Length() > 3)
            {
                MessageBox.Show("摇一摇");
                _accelerometer.Dispose();
            }

        }



        void ApplicationBar_StateChanged(object sender, ApplicationBarStateChangedEventArgs e)
        {
            if (ApplicationBar.BackgroundColor != Colors.White)
                ApplicationBar.BackgroundColor = Colors.White;
            else
                ApplicationBar.BackgroundColor = Colors.Transparent;


        }

        void aboutMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AboutPage.xaml", UriKind.Relative));
        }

        void leadingInCourseMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("leading in");
        }

        void settingsMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/CoursePageSettings.xaml", UriKind.Relative));
        }

        void CoursePage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (DetailCanvas.Visibility == Visibility.Visible)
            {
                DetailCanvas.Visibility = Visibility.Collapsed;
                e.Cancel = true;
            }
        }

        private void InitializeColor()//初始化颜色值
        {
            CourseColorBrush[0] = new SolidColorBrush(Color.FromArgb((byte) 187, (byte) 31, (byte) 182, (byte) 110));
            CourseColorBrush[1] = new SolidColorBrush(Color.FromArgb((byte) 187, (byte) 7, (byte) 189, (byte) 230));
            CourseColorBrush[2] = new SolidColorBrush(Color.FromArgb((byte) 187, (byte) 222, (byte) 16, (byte) 16));
            CourseColorBrush[3] = new SolidColorBrush(Color.FromArgb((byte) 187, (byte) 16, (byte) 36, (byte) 166));
            CourseColorBrush[4] = new SolidColorBrush(Color.FromArgb((byte) 187, (byte) 194, (byte) 17, (byte) 83));
            CourseColorBrush[5] = new SolidColorBrush(Color.FromArgb((byte) 187, (byte) 68, (byte) 21, (byte) 122));
            CourseColorBrush[6] = new SolidColorBrush(Color.FromArgb((byte) 187, (byte) 224, (byte) 30, (byte) 92));
            CourseColorBrush[7] = new SolidColorBrush(Color.FromArgb((byte) 187, (byte) 116, (byte) 0, (byte) 255));
            CourseColorBrush[8] = new SolidColorBrush(Color.FromArgb((byte) 187, (byte) 190, (byte) 199, (byte) 15));
            CourseColorBrush[9] = new SolidColorBrush(Color.FromArgb((byte) 187, (byte) 216, (byte) 12, (byte) 198));
            CourseColorBrush[10] = new SolidColorBrush(Color.FromArgb((byte) 187, (byte) 0, (byte) 122, (byte) 204));
            CourseColorBrush[11] = new SolidColorBrush(Color.FromArgb((byte) 187, (byte) 15, (byte) 192, (byte) 60));
        }


        private void ChangeWeeks_Click(object sender, RoutedEventArgs e)
        {

        }

        //private void CourseLoadedComplete(object sender, RoutedEventArgs e)
        //{
        //    if (App.IsCourseImported == false)
        //    {
        //        LeadingInCanvas.Visibility = Visibility.Visible;
        //        return;
        //    }



        //    if (IsCourseLoaded) //防止重复加载课表
        //        return;
        //    for (int i = 0; i < MyWeeklyCourses.WeeklyCoursesCollention.Count; i++)
        //    {
        //        int temp = 0;

        //        for (int j = 0; j < MyWeeklyCourses.WeeklyCoursesCollention[i].DailyCoursesCollection.Count; j++)
        //        {
        //            Course course = MyWeeklyCourses.WeeklyCoursesCollention[i].DailyCoursesCollection[j];

        //            if (String.IsNullOrEmpty(course.CourseName))
        //            {
        //                temp += course.Length;
        //                continue;
        //            }
        //            Button button = new Button();
        //            button.Opacity = 0.9;
        //            button.Style = this.Resources["CourseButton"] as Style;
        //            button.Background = CourseColorBrush[ColorNum];
        //            button.Tag = i.ToString() + j.ToString();
        //            button.Click += ShowDetailofCourse_Click;
        //            button.Margin = new Thickness(1, 1, 1, 1);
        //            button.Content = course.Detail;


        //            Grid.SetRow(button, temp);
        //            Grid.SetColumn(button, i + 1);
        //            Grid.SetRowSpan(button, course.Length);
        //            CourseGrid.Children.Add(button);
        //            temp += course.Length;

                    
        //            ColorNum++;
        //            if (ColorNum >= 12)
        //                ColorNum = 0;
        //        }

        //    }
        //    IsCourseLoaded = true;
        //    _accelerometer.Start();
        //}

        private void ShowDetailofCourse_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            int i = Convert.ToInt32(btn.Tag.ToString()[0]) - 48;
            int j = Convert.ToInt32(btn.Tag.ToString()[1]) - 48;


            Course myCourse = MyWeeklyCourses.WeeklyCoursesCollention[i].DailyCoursesCollection[j];
            if (String.IsNullOrEmpty(myCourse.CourseName)) 
                return;

            CourseNameTextBlock.Text = myCourse.CourseName;
            ClassroomTextBlock.Text = myCourse.Classroom;
            TeacherNameTextBlock.Text = myCourse.TeacherName;
            ClassHoursTextBlock.Text = myCourse.ClassHours;
            CreditsTextBlock.Text = myCourse.Credits;

            DetailofCourseGrid.Background = btn.Background;
            DetailCanvas.Visibility = Visibility.Visible;
        }


        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            if(App.WhetherChangeColor)//如果用户关闭了自动更改颜色，那么就不保存颜色状态
                IsolatedStorageSettings.ApplicationSettings["ColorNum"] = ColorNum;//保存上一次的ColorNum用于每次打开时颜色都不同
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            LoadBackgroundImage();
        }
        private void LoadBackgroundImage()
        {
            try
            {
                BitmapImage img = new BitmapImage();
                string filePath = App.BackgroundImageUri;
                using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (iso.FileExists(filePath))
                    {
                        using (var source = iso.OpenFile(filePath, FileMode.Open, FileAccess.Read))
                        {
                            img.SetSource(source);
                        }
                        ImageBrush imgBrush = new ImageBrush();
                        imgBrush.ImageSource = img;
                        LayoutRoot.Background = imgBrush;
                    }
                    else
                    {
                        MessageBox.Show("亲，没能找到背景图片！请卸载后重新安装应用！");
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\nError In\nCoursePgae.xaml\n反馈有奖");
            }

        }
        private void ClosePopup_Click(object sender, RoutedEventArgs e)
        {
            DetailCanvas.Visibility = Visibility.Collapsed;
        }




        private void LeadingIn_Click(object sender, RoutedEventArgs e)
        {

            postdata = "uname=201313030114&upwd=chengjing";
            string uri = "http://202.115.137.129/zhangkong/curl.php";
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.BeginGetRequestStream(StreamCallback, httpWebRequest);

            LeadingInButton.IsEnabled = false;
        }




        #region
        //下面进行回调函数
        ///////////////////
        private void StreamCallback(IAsyncResult result)
        {

            HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState;
            using (Stream stream = httpWebRequest.EndGetRequestStream(result))
            {
                byte[] entryBytes = Encoding.UTF8.GetBytes(postdata);
                stream.Write(entryBytes, 0, entryBytes.Length);
            }

            //这里就和上面GET方法获得回复回调一样，用 private void ResponseCallback(IAsyncResult result) 这个方法。
            httpWebRequest.BeginGetResponse(ResponseCallback, httpWebRequest);
        }
        //第二个回调函数
        private void ResponseCallback(IAsyncResult result)
        {
            Stream stream = null;

            try
            {
                //获取异步操作返回的的信息 
                HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState;
                //结束对 Internet 资源的异步请求
                WebResponse webResponse = httpWebRequest.EndGetResponse(result);
                stream = webResponse.GetResponseStream();
                using (StreamReader sr = new StreamReader(stream))
                {
                    postback = sr.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("未能连接到远程服务器，请检查本地网络!", "程序异常", MessageBoxButton.OK);

                });
                return;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }




            if (postback != "")
            {
                IsolatedStorageSettings.ApplicationSettings["postback"] = postback;
                IsolatedStorageSettings.ApplicationSettings.Save();

                //因为HttpWebRequest是异步，不在UI线程上。所以要改变UI线程上的控件属性就要用Dispatcher.BeginInvoke()。  
                Dispatcher.BeginInvoke(() =>
                {
                    try
                    {//提示：必须先切割字符串
                        //postback = "{\"day1\":{\"1\":{\"coursename\":\"\\u62a5\\u5230\\u6ce8\\u518c\",\"classroom\":null,\"xueshi\":null,\"xuefen\":null,\"lilun\":null,\"teacher\":null}}}";
                        //MessageBox.Show(postback.Length.ToString());
                        string[] allCourseData = postback.Split(new char[] { '&' }); //做字符串分割 s[0]表示第一串字符
                        

                        //把最原始的信息存入独立存储
                        for (int i = 0; i < allCourseData.Length; i++)
                        {
                            IsolatedStorageSettings.ApplicationSettings["Week" + i.ToString()] = allCourseData[i];
                        }
                        IsolatedStorageSettings.ApplicationSettings.Save();




                        for (int k = 0; k < allCourseData.Length; k++)
                        {
                            string weeklyCourseData = allCourseData[k];
                            if(weeklyCourseData == "")
                                continue;

                            JObject jsonData = JObject.Parse(weeklyCourseData);

                            WeeklyCourses weekly = new WeeklyCourses();
                            for (int i = 0; i < 7; i++)
                            {
                                DailyCourses daily = new DailyCourses();

                                for (int j = 0; j < 12;)
                                {
                                    Course course = new Course();

                                    course.CourseName = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["coursename"].ToString();
                                    if (course.CourseName == "教研" || course.CourseName == "中秋节" ||
                                        course.CourseName == "国庆节" || course.CourseName == "报到注册" ||
                                        course.CourseName == "考试周" || course.CourseName == "省计算机" ||
                                        course.CourseName == "英语等级考试" || course.CourseName == "省艺招考试"||course.CourseName=="元旦节")
                                        course.CourseName = "";

                                    course.Classroom = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["classroom"].ToString();
                                    course.CourseType = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["lilun"].ToString();
                                    course.Credits = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["xuefen"].ToString();
                                    course.ClassHours = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["xueshi"].ToString();
                                    course.TeacherName = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["teacher"].ToString();

                                    int length = 1;
                                    //循环查询下一节课是否和本节相同
                                    while (j + length < 12 && course.CourseName ==
                                           jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][
                                               (j + 1 + length).ToString()]["coursename"].ToString()
                                               && course.Classroom == jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][
                                               (j + 1 + length).ToString()]["classroom"].ToString()
                                               ) 
                                    {
                                        length++;
                                        if (length + j == 4)//跳过中午那节课
                                            j++;
                                    }


                                    j += length;


                                    course.Length = length;
                                    daily.DailyCoursesCollection.Add(course);
                                }

                                weekly.WeeklyCoursesCollention.Add(daily);
                            }
                            var dataofWeeks = JsonConvert.SerializeObject(weekly);
                            IsolatedStorageSettings.ApplicationSettings["ParsedWeek" + k.ToString()] = dataofWeeks;
                        }

                        App.IsCourseImported = true;
                        IsolatedStorageSettings.ApplicationSettings["IsCourseImported"] = App.IsCourseImported;
                        IsolatedStorageSettings.ApplicationSettings.Save();
                        LeadingInCanvas.Visibility = Visibility.Collapsed;

                        InitializeCourseGrid();

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                });
            }
            else
            {
                MessageBox.Show("课表服务器崩溃了！！！\n我们正在鞭打程序员……");
            }

        }

        #endregion

        private void ScrollView_Loaded(object sender, RoutedEventArgs e)
        {

            //判断本地是否导入了课表
            if (App.IsCourseImported == false)
            {
                LeadingInCanvas.Visibility = Visibility.Visible;//导入课表
                return;
            }
            if (IsCourseLoaded == false) 
                InitializeCourseGrid();

        }

        private void InitializeCourseGrid()
        {
            courseGrid = new Grid();
            courseGrid.Loaded += courseGrid_Loaded;

            for (int i = 0; i < App.CourseNumber + 1; i++)//加一是为了在底部留出空隙
            {
                RowDefinition rowDefinition = new RowDefinition();
                GridLength height = new GridLength(61.42);
                rowDefinition.Height = height;
                courseGrid.RowDefinitions.Add(rowDefinition);
            }

            ColumnDefinition columnDefinition1 = new ColumnDefinition();//左侧写课程数
            GridLength width1 = new GridLength(50);
            columnDefinition1.Width = width1;
            courseGrid.ColumnDefinitions.Add(columnDefinition1);

            for (int i = 0; i < 7; i++)
            {
                ColumnDefinition columnDefinition = new ColumnDefinition();
                GridLength width = new GridLength(61.42);
                columnDefinition.Width = width;
                courseGrid.ColumnDefinitions.Add(columnDefinition);
            }

            //for (int i = 0; i < App.CourseNumber; i++)
            //{
            //    TextBlock textBlock = new TextBlock();
            //    textBlock.Text = (i + 1).ToString();
            //    textBlock.TextAlignment = TextAlignment.Center;
            //    textBlock.VerticalAlignment = VerticalAlignment.Center;
            //    SolidColorBrush brush = new SolidColorBrush(Color.FromArgb((byte)255,(byte)0,(byte)191,(byte)240));
            //    textBlock.Foreground = brush;
            //    FontSize = 20;
            //    textBlock.FontFamily = new FontFamily("Microsoft YaHei");
            //    Grid.SetRow(textBlock, i);
            //    Grid.SetColumn(textBlock, 0);
            //    courseGrid.Children.Add(textBlock);
            //}
            CourseScrollViewer0.Content = courseGrid;
        }

        void courseGrid_Loaded(object sender, RoutedEventArgs e)
        {
            LoadCourseFromIsoStore();
        }
        private void LoadCourseFromIsoStore()
        {
            for (int i = 0; i < App.CourseNumber; i++)
            {
                TextBlock textBlock = new TextBlock();
                textBlock.Text = (i + 1).ToString();
                textBlock.TextAlignment = TextAlignment.Center;
                textBlock.VerticalAlignment = VerticalAlignment.Center;
                SolidColorBrush brush = new SolidColorBrush(Color.FromArgb((byte)255, (byte)0, (byte)191, (byte)240));
                textBlock.Foreground = brush;
                FontSize = 20;
                textBlock.FontFamily = new FontFamily("Microsoft YaHei");
                Grid.SetRow(textBlock, i);
                Grid.SetColumn(textBlock, 0);
                courseGrid.Children.Add(textBlock);
            }

            string dataFromIsoStore =
                Convert.ToString(IsolatedStorageSettings.ApplicationSettings["ParsedWeek" + App.WeekNumber.ToString()]);

            weeklyCourses = JsonConvert.DeserializeObject<WeeklyCourses>(dataFromIsoStore);


            for (int i = 0; i < MyWeeklyCourses.WeeklyCoursesCollention.Count; i++)
            {
                int temp = 0;

                for (int j = 0; j < MyWeeklyCourses.WeeklyCoursesCollention[i].DailyCoursesCollection.Count; j++)
                {
                    Course course = MyWeeklyCourses.WeeklyCoursesCollention[i].DailyCoursesCollection[j];

                    if (String.IsNullOrEmpty(course.CourseName))
                    {
                        temp += course.Length;
                        continue;
                    }
                    Button button = new Button();
                    button.Opacity = 0.9;
                    button.Style = this.Resources["CourseButton"] as Style;
                    button.Background = CourseColorBrush[ColorNum];
                    button.Tag = i.ToString() + j.ToString();
                    button.Click += ShowDetailofCourse_Click;
                    button.Margin = new Thickness(1, 1, 1, 1);
                    button.Content = course.Detail;


                    Grid.SetRow(button, temp);
                    Grid.SetColumn(button, i + 1);
                    Grid.SetRowSpan(button, course.Length);
                    courseGrid.Children.Add(button);
                    temp += course.Length;


                    ColorNum++;
                    if (ColorNum >= 12)
                        ColorNum = 0;
                }

            }
            IsCourseLoaded = true;
            _accelerometer.Start();
        }

        private void GestureListener_Flick(object sender, FlickGestureEventArgs e)
        {
            if (e.Angle < 45 || e.Angle > 315)
            {
                //MessageBox.Show("left");
                if (App.WeekNumber > 0)
                {
                    App.WeekNumber--;
                    courseGrid.Children.Clear();
                    LoadCourseFromIsoStore();
                }
                else
                {
                    MessageBox.Show("亲，再往前就是暑假了！");
                }

            }
            else if (e.Angle > 135 && e.Angle <= 225)
            {
                //MessageBox.Show("right");
                if (App.WeekNumber < 20)
                {
                    App.WeekNumber++;
                    courseGrid.Children.Clear();
                    LoadCourseFromIsoStore();
                }
                else
                {
                    MessageBox.Show("亲！这已经是最后一周了！");
                }
            }

        }

        private void ChangeWeekView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (IsCourseLoaded == false) 
                return;

            int newPage = MyPivot.SelectedIndex;
            if ((currentPage == 0 && newPage == 2) || (currentPage == 1 && newPage == 0) ||
                (currentPage == 2 && newPage == 1))  
            {
                //App.WeekNumber--
                App.WeekNumber--;
                if (App.WeekNumber == -1)
                    App.WeekNumber = 20;
                WeekNumberTextBlock.Text = "第" + (App.WeekNumber + 1).ToString() + "周";

                if (App.WeekNumber == Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["WeekNumber"])) 
                    CurrentWeekTextBlock.Visibility = Visibility.Visible;
                else
                    CurrentWeekTextBlock.Visibility = Visibility.Collapsed;
                    
                InitializeCourseGrid();
                //courseGrid.Children.Clear();
                //LoadCourseFromIsoStore();


                if (newPage == 0)
                {
                    CourseScrollViewer1.Content = null;
                    CourseScrollViewer0.Content = courseGrid;
                }
                else if (newPage == 1)
                {
                    CourseScrollViewer0.Content = null;
                    CourseScrollViewer2.Content = null;
                    CourseScrollViewer1.Content = courseGrid;
                }
                else
                {
                    CourseScrollViewer0.Content = null;
                    CourseScrollViewer2.Content = courseGrid;
                }

                currentPage = newPage;
            }
            else
            {
                //App.WeekNamber++
                App.WeekNumber++;
                if (App.WeekNumber == 21)
                    App.WeekNumber = 0;


                WeekNumberTextBlock.Text = "第" + (App.WeekNumber + 1).ToString() + "周";

                if (App.WeekNumber == Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["WeekNumber"]))
                    CurrentWeekTextBlock.Visibility = Visibility.Visible;
                else
                    CurrentWeekTextBlock.Visibility = Visibility.Collapsed;

                //courseGrid.Children.Clear();
                //LoadCourseFromIsoStore();
                InitializeCourseGrid();

                if (newPage == 0)
                {
                    CourseScrollViewer2.Content = null;
                    CourseScrollViewer0.Content = courseGrid;


                }

                else if (newPage == 1)
                {
                    CourseScrollViewer0.Content = null;
                    CourseScrollViewer1.Content = courseGrid;

                }
                else
                {
                    CourseScrollViewer0.Content = null;
                    CourseScrollViewer1.Content = null;
                    CourseScrollViewer2.Content = courseGrid;
                }

                currentPage = newPage;
                
            }







        }


    }


    public class LengthToHeight : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            int length = System.Convert.ToInt32(value);
            return length*64.28;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }

    public class CourseNameToOpacity : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null || value.ToString() == "")
                return 0;
            else
                return 1;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }

    public class TeacherNameToColor : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            CoursePage.ColorNum++;
            if (CoursePage.ColorNum >= 12)
                CoursePage.ColorNum = 0;
            return CoursePage.CourseColorBrush[CoursePage.ColorNum];



        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }
}